#include "stdafx.h"
#include <map>
#include <string>
#include "ddm.h"
#include "odbc.h"
#include "DBMySql.h"
#include "DBSqlite.h"

#include "../CommonFunc/CommonFunc.h"

#define DDM_VERSION        "1.1.1"
#define DDM_VERSION_NUMBER 1001001

namespace DDM
{
//----------------------------------------------------------------------------
void Database::free_rows(std::vector<DBRow*> *rows)
{
    for (size_t i = 0; i < rows->size(); i++)
    {
        DBRow *prow = rows->at(i);
        for (size_t j = 0; j < prow->cols.size(); j++)
        {
            DBCol *col = prow->cols.at(j);
            if (col->alloced) delete[] col->data;
            delete col;
        }
        delete prow;
    }
    rows->clear();
}
//----------------------------------------------------------------------------
DDM_API Database* CreateDB(DB_TYPE type)
{
    switch (type)
    {
    case DBTYPE_MYSQL:
        return new DB_MySql();
    case DBTYPE_ODBC:
        return new DB_ODBC();
    case DBTYPE_SQLITE:
        return new DBSqlite();
    }
    return NULL;
}

static LIST_HEAD(DBListHead);
DDM_API Database* GetDB(const char *dbName, DB_TYPE type)
{
    struct list_head *tmp;
    list_for_each(tmp, &DBListHead)
    {
        Database *db = list_entry(tmp, Database, list);
        if (!strncmp(db->name, dbName, sizeof(db->name))) return db;
    }
    Database *db = CreateDB(type);
    strncpy(db->name, dbName, sizeof(db->name));
    list_add_tail(&db->list, &DBListHead);
    return db;
}
DDM_API void CloseDB(const char *dbName)
{
    struct list_head *tmp, *n;
    list_for_each_safe(tmp, n, &DBListHead)
    {
        Database *db = list_entry(tmp, Database, list);
        if (!strncmp(db->name, dbName, sizeof(db->name)))
        {
            db->close();
            list_del(&db->list);
            delete db;
        }
    }
}


DDM_API const char* ddm_version(void)
{
    return DDM_VERSION;
}

DDM_API int ddm_version_number(void)
{
    return DDM_VERSION_NUMBER;
}

}
